<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
        title="货位转移明细"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('cargoSpaceTransfer:transfer') &&
              infoList.data.status === 1
            "
            @click="transfer"
            >转移</el-button
          >
          <el-button
            v-if="
              $permission('cargoSpaceTransfer:update') &&
              infoList.data.status === 1
            "
            @click="update"
            >修改</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="infoList"
              :label-width="infoList.labelWidth"
            />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" :sums="tableInfo.sums" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="false"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                :spanMethod="spanMethod"
                methodKey="groupKey"
              >
                <template v-slot:col-storeBatchNumber="scope">
                  <span
                    v-if="scope.row.isConsignBusiness === 1"
                    class="consignBusiness-text"
                    >寄</span
                  >
                  <span
                    v-if="scope.row.isEstimationStockBusiness === 1"
                    class="estimationStockBusiness-text"
                    >暂</span
                  >
                  <span>{{ scope.row.storeBatchNumber }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :info="individualInfo.info"
      :orderId="tableRow.id"
      :isConsignBusiness="isConsignBusiness"
      :ids="ids"
    />
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.id"
      @returnModify="getInfo"
    />
  </div>
</template>

<script setup name="transferOrderDetail">
import { orderOpAffairAll } from '@/api/affair'
import {
  getConsumeOrderDetailCustomizeListAll,
  transferOrderById,
  transferTransferOrder,
} from '@/api/wms.js'
import { getCustomizeSetting } from '@/api/customize'
import { selectByCodeAndDept } from '@/api/report.js'
import { doPrint } from '@/utils/exportUtil.js'
import Modify from './modify'
const IndividualDetails = defineAsyncComponent(() =>
  import('./IndividualDetails')
)
const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: function () {
      return false
    },
  },
  tableRow: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 89,
    orderId: props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const infoList = ref({
  data: {},
  fieldList: [
    { label: '单据号', value: 'orderNo', type: 'text' },
    { label: '转移仓库', value: 'depotName', type: 'text' },
    { label: '转出货位', value: 'locationNo', type: 'text' },
    { label: '转出货位类型', value: 'locationTypeValue', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
  labelWidth: '110px',
})
const modifyInfo = ref({
  visible: false,
  title: '',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    {
      label: '通用名称',
      value: 'commonName',
      minWidth: '90px',
    },
    {
      label: '产品编码',
      value: 'productCode',
      minWidth: '90px',
    },
    {
      label: '规格',
      value: 'standard',
      minWidth: '90px',
    },
    {
      label: '厂家',
      value: 'brandName',
      minWidth: '90px',
    },
    {
      label: '单位',
      value: 'unitName',
      minWidth: '90px',
    },
    {
      label: '条码类型',
      value: 'codeTypeValue',
      minWidth: '90px',
    },
    {
      label: '生产批号',
      value: 'batchNumber',
      minWidth: '90px',
    },
    {
      label: '生产日期',
      value: 'productionDate',
      minWidth: '90px',
    },
    {
      label: '失效日期',
      value: 'validityDate',
      minWidth: '90px',
    },
    {
      label: '入库批次号',
      value: 'storeBatchNumber',
      minWidth: '90px',
    },
    {
      label: '供应商',
      value: 'supplierName',
      minWidth: '90px',
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: (row, column, cellValue, index) => {
        if (row.codeType === 2 || row.codeType === 3) return '-'
        return proxy.$fn.TripartiteMethod(row, column, cellValue, index)
      },
      permission: !proxy.$permission('cargoSpaceTransfer:price'),
      minWidth: '90px',
    },
    {
      label: '可用数',
      value: 'stockAvailableQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
      minWidth: '90px',
    },
    {
      label: '转移数量',
      value: 'qty',
      minWidth: '90px',
    },
    {
      label: '转入货位',
      value: 'targetLocationNo',
      minWidth: '90px',
    },
    {
      label: '转入货位类型',
      value: 'targetLocationTypeValue',
      minWidth: '90px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: showDetail,
        show: true,
        ifRender: function (row) {
          let arr = [2, 3]
          return arr.includes(row.codeType) && row.emptyRowType !== '1'
        },
      },
    ],
  },
  sysGroup: [],
})
const individualInfo = ref({
  visible: false,
  info: {},
})
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      isSelectMerge: 1,
    },
  },
})
const isConsignBusiness = ref('')
const ids = ref('')
const popoverVisible = ref(false)
const templateArr = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return proxy.$permission('cargoSpaceTransfer:printOrderDetail')
})

onMounted(() => {
  filterInfo.value.query.queryMap.orderId.value = props.tableRow.id
  getMain()
  getCustomize()
})

//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'wmsTransferOrder',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.tableRow.id,
          },
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.tableRow.id,
    },
    data: {},
  })
  popoverVisible.value = false
}
function getInfo() {
  getMain()
  getList()
}
function transfer() {
  transferTransferOrder({
    id: infoList.value.data.id,
  }).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}
function update() {
  //修改
  modifyInfo.value.id = props.tableRow.id
  modifyInfo.value.title = '修改货位转移'
  modifyInfo.value.visible = true
}
function returnBack() {
  emit('returnBack', false)
}
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let len = tableInfo.value.fieldList.length
  let keys = new Array(len + 1)
  if (column.property === 'storeBatchNumber') {
    keys[columnIndex] = ''
  } else {
    keys = [
      'groupKey',
      'commonName',
      'productCode',
      'standard',
      'brandName',
      'unitName',
      'codeTypeValue',
      'batchNumber',
      'productionDate',
      'validityDate',
    ]
  }
  // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
  return proxy.$fn.spanMethod(tableInfo.value.data, keys, rowIndex, columnIndex)
}
function showDetail(row) {
  ids.value = row.groupConcatIds
  individualInfo.value.visible = true
  individualInfo.value.info = row
}
function getCustomize() {
  let param = {
    tableKey:
      'productBatchStockTransferOrderModify-com.slip.spd.entity.vo.wms.WmsTransferOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({ key, sysGroupLevel: data.detail[key].sysGroupLevel })
        }
      }
      arr = proxy.$fn.getSort(arr, 'sysGroupLevel')
      arr = arr.map((element) => {
        return element.key
      })
      tableInfo.value.sysGroup = arr
      if (props.tableRow.id) {
        getList()
      }
    }
  })
}
function getMain() {
  transferOrderById(props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      isConsignBusiness.value = resp.data.isConsignBusiness
    }
  })
}
function getList() {
  getConsumeOrderDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      setTableData(resp.data)
    }
  })
}
function setTableData(data) {
  data.forEach((row, index) => {
    let str = ''
    tableInfo.value.sysGroup.forEach((item) => {
      if (
        item !== 'price' &&
        item !== 'supplierId' &&
        item !== 'storeBatchNumber' &&
        item !== 'targetGoodsLocationId'
      ) {
        if (item === 'productionDate' || item === 'validityDate') {
          str = str + (row[item] || '1900-01-01') + ''
        } else {
          str = str + row[item] + ''
        }
      }
    })
    row.groupKey = str
    row._key = row.storeBatchNumber + '-' + row.supplierId + '-' + row.price
    if (row.codeType === 2 || row.codeType === 3) {
      row._key = '--'
    }
    if (row.codeType === 1 || row.codeType === 4) {
      let detail = proxy.$fn.deepClone(row)
      row.details = [detail]
    }
  })
  tableInfo.value.data = data
}
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden > .el-table) {
  overflow-y: hidden;
}
</style>
